<?php
/**
 * Created by PhpStorm.
 * User: Da Xiong
 * Date: 2018/12/5
 * Time: 10:30
 */

namespace App\Http\Controllers;


use App\Models\Address;
use App\Models\Mall;
use App\Models\MallOrders;
use App\Models\TaskLog;
use App\Models\Users;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class OrderController extends Controller
{

    /**
     * 获取订单列表
     */
    public function index(){
        $uid = auth()->guard('api')->id();
        $list = MallOrders::where('user_id',$uid)
            ->whereIn('status',[MallOrders::STATUS_1,MallOrders::STATUS_2])
            ->orderBy('updated_at','DESC')
            ->paginate(20);
        return $this->returnJson(0,'',$list);
    }

    /**
     * 创建订单
     */
    public function add(){
        $uid = auth()->guard('api')->id();
        $user = auth()->guard('api')->user();
        $shop_id = (int)request('id',0);
        $number = (int)request('number',1);
        if($number < 1){
            return $this->returnJson(1,'参数错误');
        }
        $oid = $this->build_order_no();
        DB::beginTransaction();
        try{
            $shopID = Mall::where(['id'=>$shop_id,'status'=>Mall::STATUS_1])->where('number','>',0)->first();
            if($shopID){
                $address = Address::Where(['user_id'=>$uid,'lately'=>Address::STATUS_1])
                    ->orWhere(function ($query){
                        $query->orderBy('updated_at','DESC')->get();
                    })
                    ->first();

                $orderData = [
                    'mall_id' => $shop_id,
                    'mall_thumb' => $shopID['thumb'],
                    'mall_name' => $shopID['name'],
                    'oid' => $oid,
                    'user_id' => $uid,
                    'score' => $shopID['score'],
                    'status' => MallOrders::STATUS_1,
                    'number' => $number,
                    'user_name'=> $address['name'] ?? $user['username'],
                    'user_address' => $address['address'] ?? '',
                    'user_phone' => $address['phone'] ?? '',
                ];

                $order_id = MallOrders::insertGetId($orderData);
                //更新用户积分
                $user->decrement('score', $shopID['score']);
                //更新用户积分记录（任务积分）
                $scoreLog = [
                    'user_id' => $uid,
                    'task_type' => 'order_log',
                    'info' => '兑换【'.$shopID['name'].'】X1',
                    'score' => '-'.$shopID['score'],
                    'param_id' => $order_id,
                    'created_at' => Carbon::now(),
                ];
                TaskLog::create($scoreLog);
                DB::commit();
                return $this->returnJson(0,'',['order_id'=>$order_id]);
            }
            DB::commit();
            return $this->returnJson(1,'活动已结束');
        }catch (\Exception $exception){
            DB::rollBack();
            Log::error($exception->getMessage());
            return $this->returnJson(1,'error');
        }
    }

    /**
     * 更新用户订单地址信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(){
        $order_id = (int)request('id',0);
        $address_id = (int)request('address_id',0);
        $address = Address::find($address_id);
        $orderInfo = MallOrders::where('id',$order_id)->where('status','>',MallOrders::STATUS_0)->first();
        if(!$address || !$orderInfo){
            return $this->returnJson(1,'error');
        }
        DB::beginTransaction();
        try{
            $updateDate = [
                'user_name' => $address['name'],
                'user_address' => $address['address'],
                'user_phone' => $address['phone'],
            ];
            //更新订单记录信息
            $orderInfo->update($updateDate);
            //更新用户地址最近使用地址
            Address::where('user_id',$orderInfo['user_id'])->update(['lately' => Address::STATUS_0]);
            $address->update(['lately' => Address::STATUS_1]);
            DB::commit();
            return $this->returnJson(0,'',$orderInfo);
        }catch (\Exception $exception){
            DB::rollBack();
            Log::error($exception->getMessage());
            return $this->returnJson(1,'ERROR');
        }
    }

    /**
     * 删除订单
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(){
        $order_id = (int)request('id',0);
        $orderInfo = MallOrders::where('id',$order_id)->where('status','>',MallOrders::STATUS_0)->first();
        if($orderInfo){
            $orderInfo->update('status',MallOrders::STATUS_0);
        }
        return $this->returnJson(0);
    }
    /**
     *支付订单
     */
//    public function buy(){
//        $order_id = (int)request('id',0);
//        $orderInfo = MallOrders::where('status',MallOrders::STATUS_1)->where('id',$order_id)->with('shop')->first();
//        if(!$orderInfo){
//            return $this->returnJson(1,'error');
//        }
//        $userInfo = auth()->guard('api')->user();
//        DB::beginTransaction();
//        try{
//            if($userInfo['score'] >= $orderInfo['score']){
//                //更新订单状态
//                $orderInfo->update(['status'=>MallOrders::STATUS_2]);
//                //更新用户积分
//                Users::where('id',$orderInfo['user_id'])->decrement('score', $orderInfo['score']);
//                //更新用户积分记录（任务积分）
//                $scoreLog = [
//                    'user_id' => $orderInfo['user_id'],
//                    'task_type' => 'order_log',
//                    'info' => '兑换【'.$orderInfo['shop']['name'].'】X'.$orderInfo['number'],
//                    'score' => '-'.$orderInfo['score'],
//                    'param_id' => $order_id,
//                    'created_at' => Carbon::now(),
//                ];
//                TaskLog::create($scoreLog);
//                DB::commit();
//                return $this->returnJson(0,'',$orderInfo);
//            }
//            DB::commit();
//            return $this->returnJson(1,'error:Insufficient score');
//        }catch (\Exception $exception){
//            DB::rollBack();
//            Log::error($exception->getMessage());
//            return $this->returnJson(1,'error');
//        }
//
//
//    }
}